import { Component, OnInit, Attribute } from '@angular/core';
import { FormGroup, FormBuilder, Validators, AbstractControl, Validator } from '@angular/forms';

@Component({
  selector: 'app-lesson5-two',
  templateUrl: './lesson5-two.component.html',
  styleUrls: ['./lesson5-two.component.scss']
})
export class Lesson5TwoComponent implements OnInit {
  test;
  topCode = `class Validators {
    static min(min: number): ValidatorFn
    static max(max: number): ValidatorFn
    static required(control: AbstractControl): ValidationErrors | null
    static requiredTrue(control: AbstractControl): ValidationErrors | null
    static email(control: AbstractControl): ValidationErrors | null
    static minLength(minLength: number): ValidatorFn
    static maxLength(maxLength: number): ValidatorFn
    static pattern(pattern: string | RegExp): ValidatorFn
    static nullValidator(control: AbstractControl): ValidationErrors | null
    static compose(validators: ValidatorFn[]): ValidatorFn | null
    static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null
  }`;

  html = `
  <form [formGroup]="form" (ngSubmit)="submit()">
    <div class="form-group">
      <label>真实姓名</label>
      <input type="text" formControlName="user" [ngClass]="{'is-invalid': !form.get('user').valid}" class="form-control">
      <small *ngIf="formErrors.user" class="form-text text-danger">{{formErrors.user}}</small>
    </div>
    <div class="form-group">
      <label for="exampleInputEmail1">密码</label>
      <input type="password" formControlName="password" [ngClass]="{'is-invalid': !form.get('password').valid}" class="form-control">
    </div>
    <button type="submit" class="btn btn-primary">登录</button>
  </form>`;
  ts = `import { Component, OnInit, Attribute } from '@angular/core';
  import { FormGroup, FormBuilder, Validators, AbstractControl, Validator } from '@angular/forms';

  @Component({
    selector: 'app-lesson5-two',
    templateUrl: './lesson5-two.component.html',
    styleUrls: ['./lesson5-two.component.scss']
  })
  export class Lesson5TwoComponent implements OnInit {

    form: FormGroup;
    formErrors = {
      user: ''
    };
    validationMessage = {
      user: {
        required: '真实姓名不能为空',
        pattern: '真实姓名必须是中文',
        minlength: '真实姓名最少二位',
        maxlength: '真实姓名最多四位'
      }
    };
    toSubmit = false;
    constructor(private fb: FormBuilder) {
      this.form = this.fb.group({
        user: ['', [
          Validators.required,
          Validators.pattern('^[\u4e00-\u9fa5]+$'),
          Validators.minLength(2),
          Validators.maxLength(4)
        ]],
        password: ['', Validators.required]
      });
      this.form.valueChanges.subscribe(data => this.onValueChanged());
    }

    ngOnInit() {
    }

    onValueChanged() {
      if (!this.form) {
        return;
      }
      const form = this.form;
      for (const field in this.formErrors) {
        if (field) {
          this.formErrors[field] = '';
          const control = form.get(field);
          console.log(control.errors);
          if (control && !control.valid) {
            const messages = this.validationMessage[field];
            for (const key in control.errors) {
              if (key) {
                console.log(key);
                this.formErrors[field] += messages[key] + '\\n';
              }
            }
          }
        }
      }
    }
    submit() {
      console.log(this.form.value);
    }
  }
  `;
  form: FormGroup;
  formErrors = {
    user: ''
  };
  validationMessage = {
    user: {
      required: '真实姓名不能为空',
      pattern: '真实姓名必须是中文',
      minlength: '真实姓名最少二位',
      maxlength: '真实姓名最多四位'
    }
  };
  toSubmit = false;
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      user: ['', [
        Validators.required,
        Validators.pattern('^[\u4e00-\u9fa5]+$'),
        Validators.minLength(2),
        Validators.maxLength(4)
      ]],
      password: ['', Validators.required]
    });
    this.form.valueChanges.subscribe(data => this.onValueChanged());
  }

  ngOnInit() {
  }

  onValueChanged() {
    if (!this.form) {
      return;
    }
    const form = this.form;
    for (const field in this.formErrors) {
      if (field) {
        this.formErrors[field] = '';
        const control = form.get(field);
        console.log(control.errors);
        if (control && !control.valid) {
          const messages = this.validationMessage[field];
          for (const key in control.errors) {
            if (key) {
              console.log(key);
              this.formErrors[field] += messages[key] + '\n';
            }
          }
        }
      }
    }
  }
  submit() {
    console.log(this.form.value);
  }
}
